package com.cskaoyan.service.wx;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.wx.WxCartCheck;
import com.cskaoyan.bean.wx.WxCartCheckoutVO;
import com.cskaoyan.bean.wx.WxCartData;
import com.cskaoyan.bean.wx.WxCartTotal;
import com.cskaoyan.mapper.*;
import com.cskaoyan.service.AppletCouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Kongwo
 * @description
 * @since 2022/05/08 09:22
 */

@Service
@Transactional
public class WxCartServiceImpl implements WxCartService {

    @Autowired
    MarketCartMapper marketCartMapper;

    @Autowired
    MarketGoodsMapper marketGoodsMapper;

    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;

    @Autowired
    MarketCouponMapper marketCouponMapper;

    @Autowired
    MarketAddressMapper marketAddressMapper;

    @Autowired
    MarketGrouponRulesMapper marketGrouponRulesMapper;

    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;

    /**
     * 购物车首页
     *
     * @return
     */
    @Override
    public WxCartData getCartIndex(Integer userId) {

        WxCartData wxCartData = new WxCartData();
        wxCartData.setCartList(marketCartMapper.selectAll(userId));
        List<MarketCart> cartList = wxCartData.getCartList();
        int goodsCount = 0;
        BigDecimal goodsAmount = new BigDecimal(0);
        int checkedGoodsCount = 0;
        BigDecimal checkedGoodsAmount = new BigDecimal(0);
        for (MarketCart marketCart : cartList) {
            Short number = marketCart.getNumber();
            BigDecimal price = marketCart.getPrice();
            goodsCount += number;
            goodsAmount = goodsAmount.add(price.multiply(new BigDecimal(number)));
            if (marketCart.getChecked()) {
                checkedGoodsCount += number;
                checkedGoodsAmount = checkedGoodsAmount.add(price.multiply(new BigDecimal(number)));
            }
        }
        wxCartData.setCartTotal(new WxCartTotal(checkedGoodsAmount, checkedGoodsCount, goodsAmount, goodsCount));
        return wxCartData;
    }

    /**
     * 加入购物车
     *
     * @param marketCart
     */
    @Override
    public void addCart(MarketCart marketCart) {

        Integer goodsId = marketCart.getGoodsId();
        Short number = marketCart.getNumber();
        Integer productId = marketCart.getProductId();
        Integer userId = marketCart.getUserId();

        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(goodsId);
        MarketGoodsProduct marketGoodsProduct = marketGoodsProductMapper.selectByPrimaryKey(productId);


        // 如果购物车中已经存在同样productId的商品，那么只需增加数量就可以
        if (marketCartMapper.updateNumberAdd(productId, marketCart.getNumber(), userId) != 0) {
            return;
        }
        marketCart = new MarketCart(null, userId, goodsId, marketGoods.getGoodsSn(), marketGoods.getName(), productId, new BigDecimal(marketGoodsProduct.getPrice()), number, marketGoodsProduct.getSpecifications(), null, marketGoods.getPicUrl(), null, null, null);
        marketCartMapper.insertSelective(marketCart);

    }

    /**
     * 修改购物车中商品信息
     *
     * @param marketCart
     */
    @Override
    public MarketCart updateCart(MarketCart marketCart) {

        if (marketCart.getId() == null) {
            int i = marketCartMapper.updateByProductIdKeySelective(marketCart);
            if (i == 0) {
                addCart(marketCart);
            }
            marketCart.setId(marketCartMapper.selectByProductId(marketCart));
            return marketCart;
        }
        marketCartMapper.updateByPrimaryKeySelective(marketCart);
        return marketCart;
    }

    /**
     * 删除购物车种商品
     *
     * @param productIds
     */
    @Override
    public WxCartData deleteCart(Integer[] productIds,Integer userId) {

        for (Integer productId : productIds) {
            marketCartMapper.updateCartDeleted(productId, userId);
        }
        return getCartIndex(userId);
    }

    /**
     * 修改购物车中商品是否选中
     *
     * @param wxCartCheck
     * @return
     */
    @Override
    public WxCartData updateCartChecked(WxCartCheck wxCartCheck, Integer userId) {

        Integer[] productIds = wxCartCheck.getProductIds();
        for (Integer productId : productIds) {
            marketCartMapper.updateChecked(wxCartCheck.getIsChecked(), productId, userId);
        }
        return getCartIndex(userId);
    }

    /**
     * 购物车下单页面信息显示
     * cartId=0，购物车中下单，goodslist为所有checked商品，cartId=xx，直接下单，goodslist为cartId商品
     *
     * @return
     */
    @Override
    public WxCartCheckoutVO checkoutCart(Integer cartId, Integer addressId, Integer couponId, Integer userCouponId, Integer grouponRulesId, Integer userId) {

        List<MarketCart> marketCart = new ArrayList<>();
        if (cartId == 0) {
            marketCart = marketCartMapper.selectByChecked(userId);
        } else {
            marketCart.add(marketCartMapper.selectByPrimaryKey(cartId));
        }

        BigDecimal goodsTotalPrice = new BigDecimal(0);
        for (MarketCart cart : marketCart) {
            goodsTotalPrice = goodsTotalPrice.add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));
        }


        // 获取用户当前所有状态为未使用的优惠券
        List<MarketCouponUser> couponUserList= marketCouponUserMapper.selectAvailableCoupon(userId);
        // 满足条件的折扣最大金额的优惠券的金额
        BigDecimal maxCouponPrice = new BigDecimal(0);
        //
        boolean status = false;
        Integer couponIdVO = 0;
        Integer userCouponIdVO = 0;
        // 遍历所有的优惠券，通过优惠券id来校验当前优惠券是否可用
        for (int i = 0; i < couponUserList.size(); i++) {
            MarketCouponUser marketCouponUser = couponUserList.get(i);
            Integer couponId1 = marketCouponUser.getCouponId();
            // 校验当前优惠券是否可用
            // goodsTotalPrice >= min,status = 0,deleted=0
            MarketCoupon marketCoupon = marketCouponMapper.selectAvailableCoupon(couponId1, goodsTotalPrice);
            if (marketCoupon == null) {
                couponUserList.remove(i);
                i--;
                continue;
            }
            if (couponId1.equals(couponId)) {
                status = true;
            }

            BigDecimal discount = marketCoupon.getDiscount();
            if (discount.compareTo(maxCouponPrice) > 0) {
                maxCouponPrice = discount;
                couponIdVO = couponId1;
                userCouponIdVO = marketCouponUser.getId();
            }
        }


        BigDecimal couponPrice = new BigDecimal(0);
        if (couponId == -1) {
            couponIdVO = -1;
            userCouponIdVO = -1;
        } else if (couponId == 0 || !status) {
            couponPrice = maxCouponPrice;
        } else if (couponId > 0) {
            couponPrice = marketCouponMapper.selectByPrimaryKey(couponId).getDiscount();
            couponIdVO = couponId;
            userCouponIdVO = userCouponId;
        }
        BigDecimal actualPrice = goodsTotalPrice.subtract(couponPrice);

        // 运费
        BigDecimal freightPrice = new BigDecimal(0);
        if (goodsTotalPrice.intValue() < 90) {
            freightPrice= new BigDecimal(2);
            actualPrice = actualPrice.add(freightPrice);
        }

        // 地址
        MarketAddress marketAddress;
        if (addressId == 0) {
            marketAddress = marketAddressMapper.selectDefault();
            if (marketAddress != null) {
                addressId = marketAddress.getId();
            }

        } else {
            marketAddress = marketAddressMapper.selectByPrimaryKey(addressId);
        }


        // 暂不考虑团购
        // MarketGrouponRules marketGrouponRules = marketGrouponRulesMapper.selectByPrimaryKey(grouponRulesId);

        return new WxCartCheckoutVO(actualPrice, addressId, couponUserList.size(), cartId, couponIdVO, couponPrice, freightPrice, goodsTotalPrice, new BigDecimal(0), 0, actualPrice, userCouponIdVO, marketAddress, marketCart);
    }
}
